﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SPAdvancedSearch.Editors;
using System.Web.UI.WebControls;

namespace SPAdvancedSearch.Inputs
{
    /// <summary>
    /// Defines a value control for displaying a choice drop-down list input.
    /// </summary>
    public class ChoiceValueControl : ValueControlBase
    {
        #region Fields

        private DropDownListEx _dropDownList;
        private ChoiceEditorControl _choiceEditor;

        #endregion

        #region Ctor

        /// <summary>
        /// Creates an instance of <see cref="ChoiceValueControl"/>.
        /// </summary>
        /// <param name="managedPropertyName"></param>
        public ChoiceValueControl(string managedPropertyName) : base(managedPropertyName)
        {
        }

        #endregion

        #region Methods

        /// <summary>
        /// Overridden to return a <see cref="TextBox"/>.
        /// </summary>
        /// <returns></returns>
        public override ISearchPropertyInputControl GetDisplayControl()
        {
            if (_dropDownList == null)
            {
                _dropDownList = new DropDownListEx();
                _dropDownList.Load += new EventHandler(_dropDownList_Load);
            }

            return _dropDownList;
        }

        /// <summary>
        /// Overridden to return a null value since an Editor Control is not required.
        /// </summary>
        /// <returns></returns>
        public override EditorControlBase GetEditorControl()
        {
            if (_choiceEditor == null)
                _choiceEditor = new ChoiceEditorControl(this.ManagedPropertyName);

            return _choiceEditor;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Responds to the event raised when the drop down list is loaded.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _dropDownList_Load(object sender, EventArgs e)
        {
            if (_dropDownList.Items.Count == 0)
            {
                ChoiceEditorControl choiceEditor = this.GetEditorControl() as ChoiceEditorControl;

                foreach (string choice in choiceEditor.Choices)
                {
                    _dropDownList.Items.Add(new ListItem(choice, choice));
                }

                _dropDownList.Items.Insert(0, new ListItem("- All -", string.Empty));
            }
        }

        #endregion

    }
}
